<template>
  <el-card header="部署的环境统计">
    <el-form :inline="true">
      <el-form-item label="选择日期：">
        <el-date-picker
          v-model="timeRange"
          type="daterange"
          unlink-panels
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :shortcuts="shortcuts"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchEnvData()"  :loading="loading">查询</el-button>
      </el-form-item>
    </el-form>

    <div v-loading="loading">
      <div style="background-color: #bae7ff; height: 35px; display: flex; align-items: center; font-size: 12px">
      <span style="padding: 15px;">
        👍 真棒！这些时间内一共给{{ envTotal.customer }}个客户部署了{{ envTotal.env }}套环境，继续加油哦~
      </span>
      </div>
      <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
    </div>

  </el-card>
</template>

<script setup lang="ts">
import {shortcuts} from "@/config/dateDict"
import { truncateText } from "@/utils/index"
import {ref, onMounted, reactive} from "vue"
import {init as echartsInit, ECharts, EChartsOption} from "echarts"
import {getEnvDataApi} from "@/api/customer/dashboard";
import {formatDate, formatTimestamp} from "@/utils";


const endDate = new Date(); // 当前日期
const startDate = new Date();
// startDate.setFullYear(endDate.getFullYear() - 1); // 设置开始日期为一年前
startDate.setMonth(startDate.getMonth() - 6); // 设置开始日期为六个月前
const timeRange = ref([])
timeRange.value.push(formatDate(startDate))
timeRange.value.push(formatDate(endDate))
const chartContainer = ref(null);
let chart: ECharts | null = null


const envData = ref<any>("")
const loading = ref(false)
const envTotal = reactive({
  customer: 0,
  env: 0,
})

async function fetchEnvData() {
  loading.value = true
  let startTimestamp
  let endTimestamp

  if (
    timeRange.value != null &&
    typeof timeRange.value === "object" &&
    Object.keys(timeRange.value).length === 2
  ) {
    let s = timeRange.value[0]
    let e = timeRange.value[1]
    startTimestamp = formatTimestamp(s) - (60 * 60 * 8)
    endTimestamp = formatTimestamp(e) - (60 * 60 * 8)

  }
  try {
    const res = await getEnvDataApi({
      startTime: startTimestamp || undefined,
      endTime: endTimestamp || undefined,
    })
    if (res) {
      envData.value = res.data.list
      if (chartContainer.value) {
        chart = echartsInit(chartContainer.value, null, {renderer: "svg"});
        chart.setOption(getChartOption());

        // 初始化总和和整合列表
        const customerList = [];
        envTotal.env = 0
        // 遍历数据对象的每个环境
        for (const env in envData.value) {
          if (Object.hasOwnProperty.call(envData.value, env)) {
            const e = envData.value[env];

            // 遍历当前环境的数据项
            for (const item of e) {
              envTotal.env += item[1]; // 累加第二个元素
              customerList.push(...item[2]); // 合并第三个元素到names列表
            }
          }
        }

        const uniqueArr = [...new Set(customerList)];
        envTotal.customer = uniqueArr.length
      }
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await fetchEnvData(); // 获取后端数据
});


const getChartOption = (): EChartsOption => {
  const seriesData = Object.keys(envData.value).map(key => {
    return {
      name: key,
      type: 'line',
      data: envData.value[key].map(item => [parseInt(item[0]), item[1], item[2]]),
      smooth: true,
    };
  });

  // 明确指定横轴刻度
  const xAxisData = envData.value["POC环境"].map(item => new Date(parseInt(item[0])));

  return {
    xAxis: {
      type: 'time',
      data: xAxisData, // 指定刻度数据
      minInterval: 1000 * 60 * 60 * 24 * 30,
      axisLabel: {
        // 最左边和最右边是否显示数据，不需要显示，先注释，不足三个月的话x轴显示的会重复
        // showMinLabel: true,
        // showMaxLabel: true,
        rotate: 20,
        padding: [20, -20, 0, 0],
        formatter: function (value) {
          const date = new Date(value);
          const year = date.getFullYear();
          const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 补零
          return `${year}-${month}`;
        },
      },
    },
    yAxis: {
      type: 'value',
    },
    series: seriesData,
    tooltip: {
      trigger: "axis",
      formatter: function (params) {
        let tooltipContent = '<div>'; // 自定义 tooltip 样式
        tooltipContent += params[0].axisValueLabel.split(" ")[0] + "<br/>";

        params.forEach(function (item) {
          let customers = item.value[2].join(",")
          let value = item.value[1]

          if (customers !== "") {
            value = `${value}&nbsp;【${customers}】`
            value = truncateText(value,50)
          }

          tooltipContent += `
        <div>
        <span>${item.marker}</span>
          <div style="min-width: 500px;display: inline;margin-right: 20px;">${item.seriesName}</div>
          <span style="float: right">${value}</span>
        </div>
      `;
        });

        tooltipContent += '</div>'; // 结束自定义 tooltip 样式

        return tooltipContent;
      },
    },
    legend: {
      show: true,
      top: 'bottom'
    },
  }
}


</script>

<style scoped lang="scss">

</style>
